/**
 * 
 */

//本地存储类
var BaseLocalStorage = function(preId, timeSign) {
    this.preId = preId;
    this.timeSign = timeSign || '|-|';
}

// 在dao内部保存操作返回状态供日后调用
BaseLocalStorage.prototype = {
    status: {
        SUCCESS: 0,
        FAILURE: 1,
        OVERFLOW: 2,
        TIMEOUT: 3
    },
    storage: localStorage || window.localStorage,
    getKey: function(key) {
        return this.preId + key;
    },
    set: function(key, value, cb, time) {
        var status = this.status.SUCCESS,
            key = this.getKey(key);
        try {
            time = new Date(time).getTime() || time.getTime();
        } catch(e) {
            time = new Date().getTime() + 1000 * 60 * 60 * 24 * 31;
        }
        try {
            this.storage.setItem(key, time + this.timeSign + value);
        } catch (error) {
            status = this.status.OVERFLOW;
        }
        cb && cb.call(this, status, key, value);
    },
    get: function(key, cb) {
        var status = this.status.SUCCESS,
            key = this.getKey(key),
            value = null,
            timeSignLen = this.timeSign.length,
            that = this,
            index,
            time,
            retult;
        try {
            value = that.storage.getItem(key);
        } catch (e) {
            result = {
                status: that.status.FAILURE,
                value: null
            };
            cb && cb.call(this, result.status, result.value);
            return result;
        }
        if (value) {
            index = value.indexOf(that.timeSign);
            time = +value.slice(0, index);
            if (new Date(time).getTime() > new Date().getTime() || time == 0) {
                value = value.slice(index + timeSignLen);
            } else {
                value = null;
                status = that.status.TIMEOUT;
                that.remove(key);
            }
        } else {
            status = that.status.FAILURE;
        }
        result = {
            status: status,
            value: value
        }
        cb && cb.call(this, result.status, resizeBy.value);
        return result;
    },
    remove: function(key, cb) {
        var status = this.status.FAILURE,
            key = this.getKey(key),
            value = null;
        try {
            value = this.storage.getItem(key);
        } catch (error) {
            if (value) {
                try {
                    this.storage.removeItem(key);
                    status = this.status.SUCCESS;
                } catch (error) {
                }
            }
            cb && cb.call(this, status, status > 0 ? null : value.slice(value.indexOf(this.timeSign) + this.timeSign.length));
        }
    }
}

var LS = new BaseLocalStorage('LS_');

